package com.gitee.chili.leisure.message;

import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.core.AbstractDefaultMessage;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.exception.NotFoundMemberException;
import com.gitee.chili.leisure.game.Player;
import com.gitee.chili.leisure.model.HallModel;
import com.gitee.chili.leisure.model.MessageCmdEnum;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * 处理投票信息
 *
 * @author week solider
 * @since 2020.09.14
 */
@Slf4j
public class VoteProcessor extends AbstractDefaultMessage {

    private boolean isAgree;

    @Override
    protected void decoder(byte[] body) throws InvalidProtocolBufferException {
        HallModel.DealVoteCmd dealVote = HallModel.DealVoteCmd.parseFrom(body);
        isAgree = dealVote.getIsAgree();
    }

    @Override
    public Packet parseBody() {
        Optional<? extends Player> optional = RoomManager.obtain(getRoomNum())
                .getPlayers().stream().filter(p -> p.getUserId().equals(getMemberId())).findFirst();

        if(!optional.isPresent()){
            log.error("玩家ID: {} , 缓存丢失", getMemberId());
            throw new NotFoundMemberException("缓存丢失");
        }

        Player player = optional.get();

        HallModel.NotifyVoteResult.Builder builder = HallModel.NotifyVoteResult.newBuilder();
        builder.setIsAgree(isAgree)
                .setSeatNum(player.getPosition());

        return Packet.newPacket(MessageCmdEnum.Command.NOTIFY_VOTE_INFO, builder.build().toByteArray());
    }

    public boolean isAgree() {
        return isAgree;
    }
}
